{{define "head"}}
<style>
    .search-input:focus {
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    .tag {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        margin: 0.25rem;
        border-radius: 9999px;
        font-size: 0.875rem;
        font-weight: 500;
    }
    .tag-blue {
        background-color: #EBF5FF;
        color: #2B6CB0;
    }
    .tag-green {
        background-color: #F0FFF4;
        color: #2F855A;
    }
    .tag-purple {
        background-color: #FAF5FF;
        color: #6B46C1;
    }
    /* 添加模态框样式 */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 50;
    }
    .modal-container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 51;
    }
    .modal-content {
        background-color: white;
        padding: 1.5rem;
        border-radius: 0.5rem;
        max-width: 32rem;
        width: 100%;
        margin: 1rem;
    }
    .checkbox-wrapper {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem;
    }
    .checkbox-wrapper input[type="checkbox"] {
        width: 1rem;
        height: 1rem;
        border-radius: 0.25rem;
        border-color: #D1D5DB;
    }
</style>
{{end}}

{{define "content"}}
<div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
    <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-900">历史记录</h1>
            <div class="flex gap-2">
                <button id="batchDeleteBtn" onclick="confirmBatchDelete()" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 hidden">
                    <i class="fas fa-trash mr-2"></i>批量删除
                </button>
                <a href="/generate" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    <i class="fas fa-plus mr-2"></i>生成新文章
                </a>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="flex flex-col sm:flex-row gap-4 mb-6">
            <div class="flex-1">
                <div class="relative">
                    <input type="text" id="searchInput" placeholder="搜索文章标题或关键词..."
                        class="search-input block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm pl-10">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fas fa-search text-gray-400"></i>
                    </div>
                </div>
            </div>
            <div class="w-full sm:w-48">
                <select id="sortSelect"
                    class="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                    <option value="date">按生成时间排序</option>
                    <option value="title">按标题排序</option>
                </select>
            </div>
        </div>

        <!-- 文章列表 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <div class="checkbox-wrapper">
                                <input type="checkbox" id="selectAll" class="form-checkbox">
                            </div>
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">关键词</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">栏目</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">生成时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {{range .records}}
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="checkbox-wrapper">
                                <input type="checkbox" class="form-checkbox article-checkbox" data-id="{{.ID}}">
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{.ID}}</td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900">
                            <div class="max-w-[340px] break-words">{{.Title}}</div>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500">
                            <div class="max-w-[340px] break-words">{{.Keywords}}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{if .Category}}
                                {{if index $.categoryMap .Category}}
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                        {{index $.categoryMap .Category}}
                                    </span>
                                {{else}}
                                    <span class="text-gray-400">{{.Category}}</span>
                                {{end}}
                            {{else}}
                                <span class="text-gray-400">-</span>
                            {{end}}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{if eq .Status 0}}
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">未发布</span>
                            {{else}}
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已发布</span>
                            {{end}}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{.CreatedAt.Format "2006-01-02 15:04:05"}}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <a href="/history/{{.ID}}" class="text-blue-600 hover:text-blue-900 mr-4">
                                <i class="fas fa-eye mr-1"></i>查看
                            </a>
                            {{if eq .Status 0}}
                            <button onclick="confirmPublish({{.ID}})" class="text-green-600 hover:text-green-900 mr-4">
                                <i class="fas fa-paper-plane mr-1"></i>发布
                            </button>
                            {{end}}
                            <button onclick="confirmDelete({{.ID}})" class="text-red-600 hover:text-red-900">
                                <i class="fas fa-trash mr-1"></i>删除
                            </button>
                        </td>
                    </tr>
                    {{end}}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="mt-6 flex justify-between items-center">
            <div class="text-sm text-gray-700">
                显示第 <span class="font-medium">{{.start}}</span> 到 <span class="font-medium">{{.end}}</span> 条，共 <span class="font-medium">{{.total}}</span> 条记录
            </div>
            <div class="flex space-x-2">
                {{if .prevPage}}
                <a href="{{.prevPage}}" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    <i class="fas fa-chevron-left mr-1"></i>上一页
                </a>
                {{end}}
                {{if .nextPage}}
                <a href="{{.nextPage}}" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    下一页<i class="fas fa-chevron-right ml-1"></i>
                </a>
                {{end}}
            </div>
        </div>
    </div>
</div>

<!-- 删除确认对话框 -->
<div id="deleteModal" class="fixed inset-0 z-50 hidden">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-content">
            <div class="sm:flex sm:items-start">
                <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                </div>
                <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">确认删除</h3>
                    <div class="mt-2">
                        <p class="text-sm text-gray-500">确定要删除这篇文章吗？此操作无法撤销。</p>
                    </div>
                </div>
            </div>
            <div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
                <button type="button" id="confirmDelete" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                    删除
                </button>
                <button type="button" onclick="closeDeleteModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 发布确认对话框 -->
<div id="publishModal" class="fixed inset-0 z-50 hidden">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-content">
            <div class="sm:flex sm:items-start">
                <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-green-100 sm:mx-0 sm:h-10 sm:w-10">
                    <i class="fas fa-paper-plane text-green-600"></i>
                </div>
                <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="publish-modal-title">确认发布</h3>
                    <div class="mt-2">
                        <p class="text-sm text-gray-500">确定要发布这篇文章吗？发布后将立即上线。</p>
                    </div>
                </div>
            </div>
            <div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
                <button type="button" id="confirmPublish" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm">
                    发布
                </button>
                <button type="button" onclick="closePublishModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 批量删除确认对话框 -->
<div id="batchDeleteModal" class="fixed inset-0 z-50 hidden">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-content">
            <div class="sm:flex sm:items-start">
                <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                </div>
                <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">确认批量删除</h3>
                    <div class="mt-2">
                        <p class="text-sm text-gray-500">确定要删除选中的文章吗？此操作无法撤销。</p>
                    </div>
                </div>
            </div>
            <div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
                <button type="button" id="confirmBatchDelete" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                    删除
                </button>
                <button type="button" onclick="closeBatchDeleteModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>
{{end}}

{{define "scripts"}}
<script>
let currentArticleId = null;

function confirmDelete(id) {
    currentArticleId = id;
    const modal = document.getElementById('deleteModal');
    modal.classList.remove('hidden');
    modal.style.display = 'block';
}

function closeDeleteModal() {
    const modal = document.getElementById('deleteModal');
    modal.classList.add('hidden');
    modal.style.display = 'none';
    currentArticleId = null;
}

document.getElementById('confirmDelete').addEventListener('click', async function() {
    if (!currentArticleId) return;
    
    try {
        const response = await fetch(`/history/${currentArticleId}`, {
            method: 'DELETE'
        });
        console.log('Response:', response);
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('删除失败，请重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('删除失败，请重试');
    } finally {
        closeDeleteModal();
    }
});

function confirmPublish(id) {
    currentArticleId = id;
    const modal = document.getElementById('publishModal');
    modal.classList.remove('hidden');
    modal.style.display = 'block';
}

function closePublishModal() {
    const modal = document.getElementById('publishModal');
    modal.classList.add('hidden');
    modal.style.display = 'none';
    currentArticleId = null;
}

document.getElementById('confirmPublish').addEventListener('click', async function() {
    if (!currentArticleId) return;
    
    try {
        const response = await fetch(`/publish/${currentArticleId}`, {
            method: 'POST'
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('发布失败，请重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('发布失败，请重试');
    } finally {
        closePublishModal();
    }
});

// 搜索功能
document.getElementById('searchInput').addEventListener('input', function(e) {
    const searchText = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const title = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
        const keywords = row.querySelector('td:nth-child(4)').textContent.toLowerCase();
        
        if (title.includes(searchText) || keywords.includes(searchText)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
});

// 排序功能
document.getElementById('sortSelect').addEventListener('change', function(e) {
    const sortBy = e.target.value;
    const tbody = document.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    rows.sort((a, b) => {
        if (sortBy === 'date') {
            const dateA = new Date(a.querySelector('td:nth-child(6)').textContent);
            const dateB = new Date(b.querySelector('td:nth-child(6)').textContent);
            return dateB - dateA;
        } else {
            const titleA = a.querySelector('td:nth-child(3)').textContent;
            const titleB = b.querySelector('td:nth-child(3)').textContent;
            return titleA.localeCompare(titleB);
        }
    });
    
    rows.forEach(row => tbody.appendChild(row));
});

// 批量删除相关功能
let selectedArticles = new Set();

// 全选/取消全选
document.getElementById('selectAll').addEventListener('change', function(e) {
    const checkboxes = document.querySelectorAll('.article-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = e.target.checked;
        const articleId = checkbox.getAttribute('data-id');
        if (e.target.checked) {
            selectedArticles.add(articleId);
        } else {
            selectedArticles.delete(articleId);
        }
    });
    updateBatchDeleteButton();
});

// 单个文章选择
document.querySelectorAll('.article-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', function(e) {
        const articleId = this.getAttribute('data-id');
        if (this.checked) {
            selectedArticles.add(articleId);
        } else {
            selectedArticles.delete(articleId);
            document.getElementById('selectAll').checked = false;
        }
        updateBatchDeleteButton();
    });
});

function updateBatchDeleteButton() {
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    if (selectedArticles.size > 0) {
        batchDeleteBtn.classList.remove('hidden');
    } else {
        batchDeleteBtn.classList.add('hidden');
    }
}

function confirmBatchDelete() {
    if (selectedArticles.size === 0) return;
    const modal = document.getElementById('batchDeleteModal');
    modal.classList.remove('hidden');
    modal.style.display = 'block';
}

function closeBatchDeleteModal() {
    const modal = document.getElementById('batchDeleteModal');
    modal.classList.add('hidden');
    modal.style.display = 'none';
}

document.getElementById('confirmBatchDelete').addEventListener('click', async function() {
    if (selectedArticles.size === 0) return;
    
    try {
        const response = await fetch('/history', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                ids: Array.from(selectedArticles)
            })
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('批量删除失败，请重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('批量删除失败，请重试');
    } finally {
        closeBatchDeleteModal();
    }
});
</script>
{{end}}